<script setup>
  import { ref, reactive } from "vue";
  import HelloWorld from "./components/HelloWorld.vue";
  let wsClient = reactive({});
  let clientStatus = reactive({
    readyState: 0,
    isUserClose: false,
  });
  // 查看ws连接状态
  console.log("准备连接");
  function createClient() {
    wsClient = new WebSocket("ws://localhost:3000");
    clientStatus.isUserClose = false;

    // ws连接成功
    wsClient.onopen = function () {
      //timeStamp
      // type
      console.log("ws连接成功");
      console.log(this.readyState);
      clientStatus.readyState = this.readyState;
    };

    // ws发送消息
    wsClient.onmessage = function (e) {
      console.log("ws onmessage");
      // MessageEvent
      console.log(e);
      // 数据在e.data中
      console.log("接收服务器消息" + e.data);
      clientStatus.readyState = this.readyState;
      console.log(clientStatus);
    };

    // ws连接关闭
    wsClient.onclose = function () {
      // CloseEvent
      // console.log(e);
      if (clientStatus.isUserClose) {
        console.log("用户关闭ws连接");
      } else {
        console.log("服务器关闭ws连接");
      }
      console.log(this.readyState);
    };
  }
  createClient();
  // 手动关闭WS连接
  function onclose(wsClient) {
    clientStatus.isUserClose = true;
    console.log(clientStatus);
    wsClient.close();
  }
  // 发送消息
  function sendMsg(wsClient) {
    wsClient.send("from client: hello");
  }
</script>

<template>
  <div>
    <a href="https://vitejs.dev" target="_blank">
      <img src="/vite.svg" class="logo" alt="Vite logo" />
    </a>
    <a href="https://vuejs.org/" target="_blank">
      <img src="./assets/vue.svg" class="logo vue" alt="Vue logo" />
    </a>
  </div>
  <HelloWorld msg="Vite + Vue" />
  <button @click="onclose(wsClient)">关闭WS连接</button>
  <button @click="sendMsg(wsClient)">发送WS消息</button>
  <button @click="createClient">创建ws</button>
</template>

<style scoped>
  .logo {
    height: 6em;
    padding: 1.5em;
    will-change: filter;
    transition: filter 300ms;
  }
  .logo:hover {
    filter: drop-shadow(0 0 2em #646cffaa);
  }
  .logo.vue:hover {
    filter: drop-shadow(0 0 2em #42b883aa);
  }
</style>
